//
//  Student.m
//  FMDBDemo
//
//  Created by 赵成峰 on 2016/10/12.
//  Copyright © 2016年 赵成峰youdaoli. All rights reserved.
//

#import "Student.h"
#import "FMDBManager.h"

@implementation Student

- (void)createTable {
    NSString *sql = [NSString stringWithFormat:@"create table if not exists %@(uid INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(20),age int, sex varchar(20))", NSStringFromClass(self.class)];
    
    if ([FMDBManager sharedManager].database.open) {
        BOOL isSuccess = [[FMDBManager sharedManager].database executeUpdate:sql];
        if (isSuccess) {
            NSLog(@"创建成功");
        }else {
            NSLog(@"创建失败");
        }
    }
    [[FMDBManager sharedManager].database close];

}

- (void)save {
    [self createTable];
    [[FMDBManager sharedManager].database open];
    NSString *sql = [NSString stringWithFormat:@"insert into %@ values ( null,'%@', '%@', '%@')", NSStringFromClass(self.class), self.name, @(self.age), self.sex];
    BOOL insert = [[FMDBManager sharedManager].database executeUpdate:sql];
    if (insert) {
        NSLog(@"插入成功");
    }else {
        NSLog(@"插入失败");
    }
    [[FMDBManager sharedManager].database close];

}

+ (void)readData {
    [[FMDBManager sharedManager].database open];
    NSString *sql = [NSString stringWithFormat:@"select * from %@", NSStringFromClass(self.class)];
    FMResultSet *set = [[FMDBManager sharedManager].database executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    while ([set next]) {
        NSString *name = [set stringForColumn:@"name"];
        NSString *age = [set stringForColumn:@"sex"];
        NSString *sex = [set stringForColumn:@"age"];
        int uid = [set intForColumn:@"uid"];
        NSDictionary *dic = @{@"name" : name,@"age" : age,@"sex" : sex, @"uid" : @(uid)};
        NSLog(@"%@",dic);
        [array addObject:[Student mj_objectWithKeyValues:dic]];
    }
    
    NSLog(@"%@",array);
    [[FMDBManager sharedManager].database close];
    
//    [self readDataWithCondition:@"age>13"];
}

+ (void)readDataWithCondition:(NSString *)condition {
    [[FMDBManager sharedManager].database open];
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@", NSStringFromClass(self.class), condition];
    FMResultSet *set = [[FMDBManager sharedManager].database executeQuery:sql];
    NSMutableArray *array = [NSMutableArray array];
    while ([set next]) {
        NSString *name = [set stringForColumn:@"name"];
        NSString *age = [set stringForColumn:@"sex"];
        NSString *sex = [set stringForColumn:@"age"];
        NSDictionary *dic = @{@"name" : name,@"age" : age,@"sex" : sex};
        NSLog(@"dd %@",dic);
        [array addObject:[Student mj_objectWithKeyValues:dic]];
    }
    
    NSLog(@"条件查询结果 %@",array);
    [[FMDBManager sharedManager].database close];
}

@end
